package de.tum.in.eist.poll.server;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import de.tum.in.eist.poll.pub.service.PollService;
import de.tum.in.eist.poll.pub.shared.Feedback;
import de.tum.in.eist.poll.pub.shared.FeedbackExtended;
import de.tum.in.eist.poll.pub.shared.Lecture;
import de.tum.in.eist.poll.pub.shared.Lecturer;
import de.tum.in.eist.poll.pub.shared.Student;
import de.tum.in.eist.poll.pub.shared.User;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class PollServiceImpl extends RemoteServiceServlet implements
		PollService {
	public User login(String name, String password)
			throws IllegalArgumentException {
		if (!(Database.isValidInput(name, password))) {
			throw new IllegalArgumentException("Wrong user name or password!");
		}
		return Database.getUser(name);
	}

	public String submitFeedback(FeedbackExtended feedback) {
		try {
			Database.submitFeedbackToServer(feedback);
		} catch (IOException e) {
			Window.alert("IO Exception in submitFeedback()!");
			e.printStackTrace();
		}
		return "Your submission was successful!";
	}

	public List<Lecture> requestLectures(User user) {
		List lectures = new LinkedList(Database.getLectures());
		user = Database.getUser(user.getName());
		if (user instanceof Lecturer) {
			for (Lecture lecture : Database.getLectures()) {
				if (lecture.getLecturer() == user) {
					lectures.remove(lecture);
				}
			}
		}
		return lectures;
	}

	public List<Feedback> requestFeedback(Lecture lecture) {
		lecture = Database.getLecture(lecture.getLectureID());
		return Database.getFeedback(lecture);
	}
}
